import { ref } from 'vue'
import { queuedFetch } from '../utils/queuedRequest.js'

/**
 * 支行前十大贷款户数据获取
 */
export function useBranchTopLoans() {
  const isLoading = ref(false)
  const error = ref(null)

  /**
   * 获取支行前十大贷款户数据（所有支行）
   */
  const fetchBranchTopLoans = async (etlDate = '20250930') => {
    try {
      console.log(`[支行前十大贷款户] 开始获取数据，日期: ${etlDate}`)
      
      // 根据实际数据结构，使用select *暂时获取数据，然后根据位置索引解析
      const sql = `select * from audit_index_bad_loan_detail where index_name='支行前十大贷款户' and etl_dt='${etlDate}'`
      
      const postData = new URLSearchParams()
      postData.append('action', 'exesql')
      postData.append('jdbcName', 'amsedb')
      postData.append('enc', 'true')
      
      const encodedSQL = btoa(encodeURIComponent(sql))
      postData.append('sql', encodedSQL)
      
      postData.append('pageIndex', 'undefined')
      postData.append('pageSize', '1000')
      postData.append('isSys', 'false')
      postData.append('t', Date.now().toString())
      
      const apiUrl = `http://${window.location.host}/coolv/edatasource/jdbcmgr.do`
      
      const response = await queuedFetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'X-Requested-With': 'XMLHttpRequest',
          'Accept': '*/*',
          'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
        },
        body: postData.toString()
      }, {
        name: `支行前十大贷款户`,
        priority: 8
      })
      
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`)
      }
      
      const jsonResponse = await response.json()
      console.log(`[支行前十大贷款户] 查询成功，共 ${jsonResponse.datas?.length || 0} 条`)
      console.log(`[支行前十大贷款户] 前3条数据示例:`, jsonResponse.datas?.slice(0, 3))
      
      if (!jsonResponse || !jsonResponse.datas || jsonResponse.datas.length === 0) {
        console.warn('[支行前十大贷款户] 未查询到数据')
        return {}
      }
      
      // 按机构号和客户分组
      const branchMap = new Map()
      
      jsonResponse.datas.forEach(row => {
        if (!Array.isArray(row) || row.length < 15) {
          return
        }
        
        const orgNo = row[0] || ''  // 机构号
        const customerName = row[6] || '未知客户'
        const loanId = row[7] || row[9] || ''
        const contractNo = row[8] || ''
        const cardNo = row[9] || ''
        const loanDate = row[10] || ''
        const dueDate = row[11] || ''
        const currency = row[12] || 'CNY'
        const loanAmount = parseFloat(row[13]) || 0
        const balanceWan = parseFloat(row[14]) || 0
        const balance = parseFloat(row[15]) || 0
        const productCode = row[16] || ''
        const productName = row[17] || ''
        const riskLevel = row[21] || ''
        
        if (!branchMap.has(orgNo)) {
          branchMap.set(orgNo, new Map())
        }
        
        const customerMap = branchMap.get(orgNo)
        
        if (!customerMap.has(customerName)) {
          customerMap.set(customerName, {
            name: customerName,
            totalBalance: 0,
            loans: []
          })
        }
        
        const customer = customerMap.get(customerName)
        customer.totalBalance += balance
        customer.loans.push({
          loanId,
          contractNo,
          cardNo,
          loanDate,
          dueDate,
          currency,
          loanAmount,
          balanceWan,
          balance,
          productCode,
          productName,
          riskLevel,
          rawData: row
        })
      })
      
      // 转换为按机构号分组的数据结构
      const result = {}
      branchMap.forEach((customerMap, orgNo) => {
        const customers = Array.from(customerMap.values()).map(customer => ({
          name: customer.name,
          value: customer.totalBalance,
          loans: customer.loans,
          loanCount: customer.loans.length
        }))
        
        customers.sort((a, b) => b.value - a.value)
        result[orgNo] = customers
      })
      
      console.log('[支行前十大贷款户] 数据处理完成，共', Object.keys(result).length, '个支行')
      console.log('[支行前十大贷款户] 机构号列表:', Object.keys(result))
      console.log('[支行前十大贷款户] 第一个支行数据示例:', result[Object.keys(result)[0]])
      return result
    } catch (err) {
      console.error('[支行前十大贷款户] 获取数据失败:', err)
      error.value = err
      throw err
    }
  }

  /**
   * 获取支行前十大不良贷款户数据（所有支行）
   */
  const fetchBranchTopBadLoans = async (etlDate = '20250930') => {
    try {
      console.log(`[支行前十大不良贷款户] 开始获取数据，日期: ${etlDate}`)
      
      // 根据实际数据结构，使用select *暂时获取数据，然后根据位置索引解析
      const sql = `select * from audit_index_bad_loan_detail where index_name='支行前十大不良贷款户' and etl_dt='${etlDate}'`
      
      const postData = new URLSearchParams()
      postData.append('action', 'exesql')
      postData.append('jdbcName', 'amsedb')
      postData.append('enc', 'true')
      
      const encodedSQL = btoa(encodeURIComponent(sql))
      postData.append('sql', encodedSQL)
      
      postData.append('pageIndex', 'undefined')
      postData.append('pageSize', '1000')
      postData.append('isSys', 'false')
      postData.append('t', Date.now().toString())
      
      const apiUrl = `http://${window.location.host}/coolv/edatasource/jdbcmgr.do`
      
      const response = await queuedFetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'X-Requested-With': 'XMLHttpRequest',
          'Accept': '*/*',
          'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
        },
        body: postData.toString()
      }, {
        name: `支行前十大不良贷款户`,
        priority: 8
      })
      
      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`)
      }
      
      const jsonResponse = await response.json()
      console.log(`[支行前十大不良贷款户] 查询成功，共 ${jsonResponse.datas?.length || 0} 条`)
      console.log(`[支行前十大不良贷款户] 前3条数据示例:`, jsonResponse.datas?.slice(0, 3))
      
      if (!jsonResponse || !jsonResponse.datas || jsonResponse.datas.length === 0) {
        console.warn('[支行前十大不良贷款户] 未查询到数据')
        return {}
      }
      
      // 按机构号和客户分组（逻辑同前十大贷款户）
      const branchMap = new Map()
      
      jsonResponse.datas.forEach(row => {
        if (!Array.isArray(row) || row.length < 15) {
          return
        }
        
        const orgNo = row[0] || ''
        const customerName = row[6] || '未知客户'
        const loanId = row[7] || row[9] || ''
        const contractNo = row[8] || ''
        const cardNo = row[9] || ''
        const loanDate = row[10] || ''
        const dueDate = row[11] || ''
        const currency = row[12] || 'CNY'
        const loanAmount = parseFloat(row[13]) || 0
        const balanceWan = parseFloat(row[14]) || 0
        const balance = parseFloat(row[15]) || 0
        const productCode = row[16] || ''
        const productName = row[17] || ''
        const riskLevel = row[21] || ''
        
        if (!branchMap.has(orgNo)) {
          branchMap.set(orgNo, new Map())
        }
        
        const customerMap = branchMap.get(orgNo)
        
        if (!customerMap.has(customerName)) {
          customerMap.set(customerName, {
            name: customerName,
            totalBalance: 0,
            loans: []
          })
        }
        
        const customer = customerMap.get(customerName)
        customer.totalBalance += balance
        customer.loans.push({
          loanId,
          contractNo,
          cardNo,
          loanDate,
          dueDate,
          currency,
          loanAmount,
          balanceWan,
          balance,
          productCode,
          productName,
          riskLevel,
          rawData: row
        })
      })
      
      // 转换为按机构号分组的数据结构
      const result = {}
      branchMap.forEach((customerMap, orgNo) => {
        const customers = Array.from(customerMap.values()).map(customer => ({
          name: customer.name,
          value: customer.totalBalance,
          loans: customer.loans,
          loanCount: customer.loans.length
        }))
        
        customers.sort((a, b) => b.value - a.value)
        result[orgNo] = customers
      })
      
      console.log('[支行前十大不良贷款户] 数据处理完成，共', Object.keys(result).length, '个支行')
      console.log('[支行前十大不良贷款户] 机构号列表:', Object.keys(result))
      console.log('[支行前十大不良贷款户] 第一个支行数据示例:', result[Object.keys(result)[0]])
      return result
    } catch (err) {
      console.error('[支行前十大不良贷款户] 获取数据失败:', err)
      error.value = err
      throw err
    }
  }

  return {
    isLoading,
    error,
    fetchBranchTopLoans,
    fetchBranchTopBadLoans
  }
}



